using System.Collections;
using System;

namespace cuberga.Workflow
{
    public class Schema
    {
        private Process _startPoint;
        private Process _finishPoint;
        private ArrayList _processes = new ArrayList();
        public LogSubscriber _log = new LogSubscriber();
        
        public void Start()
        {
            // ToDo - make it smart
            _startPoint.SetMarker();

            while (!_finishPoint.IsReadyToPerform)
            {
                //for (int i = 0; i < 20; i++) { // for debug purposes
                Process candidat = GetProcessToPerform();

                candidat.Perform();
            }
        }

        public void MarkAsStartPoint(Process process)
        {
            _startPoint = process;
        }

        public void MarkAsFinishPoint(Process process)
        {
            _finishPoint = process;
        }

        public void AddProcess(Process process)
        {
            _processes.Add(process);
            process.Subscribe(_log);
            //process.SetParent(this);
        }

        

        private Process GetProcessToPerform()
        {
            Process candidate = null;

            foreach (Process curProcess in _processes)
            {
                if (curProcess.IsReadyToPerform)
                {
                    candidate = curProcess;
                    break;
                }
            }

            if (candidate == null)
            {
                throw new NullReferenceException("There is no processes to perform");
            }

            return candidate;
        }
    }
}
